package com.ncs.cns.business.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class CompressionImageUtil {
	public static Bitmap compressionImg(String path,Integer width,Integer height){
		BitmapFactory.Options opt = new BitmapFactory.Options();
		Bitmap result = null;
		opt.inJustDecodeBounds = true;
		Bitmap bm = BitmapFactory.decodeFile(path,opt);	
		opt.inJustDecodeBounds = false;
		opt.inPreferredConfig =  Bitmap.Config.RGB_565;
		opt.inSampleSize = 4;
		try{
			if(width == null || height == null){				
				result = BitmapFactory.decodeFile(path,opt);
			}
			else{
				opt.outHeight = height;
				opt.outWidth = width;
				result = BitmapFactory.decodeFile(path,opt);	
			}
		}catch(OutOfMemoryError e){
			
		}
		return result;
	}
	
	public static byte[] compressionImgSize(Bitmap bm){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  
        int options = 100;  
        while ( baos.toByteArray().length / 1024>500) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            baos.reset();//重置baos即清空baos  
            bm.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
            if(options<0)break;
        }  
        return baos.toByteArray();
	}
	public static int  getCompressionImgSize(Bitmap bm){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  
        int options = 100;  
        while ( baos.toByteArray().length / 1024>500) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
            baos.reset();//重置baos即清空baos  
            bm.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中  
            options -= 10;//每次都减少10  
            if(options<0)break;
        }  
        return options;
	}
	
	
	public static InputStream compressImg(String path){
		File file = new File(path);
		int size = path.length() / 1024;
         FileInputStream fis;
        
        int fileLen = 0;
		try {
			fis = new FileInputStream(file);
			fileLen = fis.available();
			fileLen = fileLen / 1024;
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		if(fileLen > 500){
			Bitmap bm = getSmallBitmap(path);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  
			bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
			return new ByteArrayInputStream(baos.toByteArray());
		}else{
			InputStream input = null;
			try {
				input = new FileInputStream(file);
				byte[] byt = new byte[input.available()];
				input.read(byt);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return input;
		}	
		
	}
	
	public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;
	    if (height > reqHeight || width > reqWidth) {
	             final int heightRatio = Math.round((float) height/ (float) reqHeight);
	             final int widthRatio = Math.round((float) width / (float) reqWidth);
	             inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
	    }
	   return inSampleSize;
	}
	
	public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
	    options.inSampleSize = calculateInSampleSize(options, 480, 800);
	    options.inPreferredConfig = Bitmap.Config.RGB_565;
	    options.inJustDecodeBounds = false;
	    return BitmapFactory.decodeFile(filePath, options);
	}
	
	public static String getSmallImgPath(String path){
		File file = new File(path);
        FileInputStream fis;        
        int fileLen = 0;
		try {
			fis = new FileInputStream(file);
			fileLen = fis.available();
			fileLen = fileLen / 1024;
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		if(fileLen < 500){return path;}
		
		Bitmap bm = getSmallBitmap(path);
		File filePath = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + "CNSUploadImg" +File.separator);
		if (!filePath.exists())
			filePath.mkdir();
		String fileName = System.currentTimeMillis()+"im";
		File newFile = new File(filePath, fileName);
		BufferedOutputStream out = null;
		int size = getCompressionImgSize(bm);
		try {
			out = new BufferedOutputStream(
					new FileOutputStream(newFile));
			bm.compress(Bitmap.CompressFormat.JPEG, size, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filePath+ File.separator+fileName;
	}
}
